package com.gdk.ksoft.ui.reporters;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.gdk.ksoft.R;
import com.gdk.ksoft.assembly.dbhelper.FreporterDbHelper;
import com.gdk.ksoft.ui.reporters.adapters.GoodsStockAdapter;
import com.gdk.ksoft.ui.works.FindbyBrandActivity;
import com.gdk.ksoft.assembly.dialog.MessageBox;
import com.gdk.ksoft.assembly.utils.system.SQLiteUtils;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.lidroid.xutils.view.annotation.event.OnCompoundButtonCheckedChange;
import com.lidroid.xutils.view.annotation.event.OnItemClick;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 商品库存查询
 */
public class GoodsStockActivity extends Activity {

    public static final int PAGE_COUNT = 20;//每页显示20条

    @ViewInject(R.id.pgoodsStock_etSearch)private EditText etSearch;//搜索框
    @ViewInject(R.id.pgoodsStock_lstGoods)private ListView lstGoods;//商品列表
    private int clickCount = 0,curIndex = -1;
    private List<HashMap<String,Object>> goodsStock = new ArrayList<>();//商品库存信息
    private List<HashMap<String,Object>> tmpGoodsStock = new ArrayList<>();//商品库存信息
    private GoodsStockAdapter goodsStockAdapter;//商品库存信息数据适配器
    private DbUtils dbUtils;//数据库操作对象
    private int currentPageIndex = 0,pageCount = 0;//当前页码,总页数
    private boolean isHasStock = true,isHasNegative = false;//默认查询有库存的,默认负库存为false
    private int operType = 0;//操作类型 1 - 搜索关键字  2-全部   3-品牌
    private int recorBrandId = 0;//记录的品牌号

    private static final int MSG_REFRESH_GOODS_STOCK_LISTVIEW = 0X0001;//刷新商品库存列表
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch(msg.what){
                case MSG_REFRESH_GOODS_STOCK_LISTVIEW:
                    tmpGoodsStock.clear();//清空元数据
                    goodsStock.clear();//清空列表数据
                    goodsStockAdapter.notifyDataSetChanged();//刷新列表
                    tmpGoodsStock.addAll((List<HashMap<String,Object>>)msg.obj);
                    currentPageIndex = 0;//置0页码
                    int dataLen = tmpGoodsStock.size();
                    pageCount = dataLen%PAGE_COUNT == 0?dataLen/PAGE_COUNT:dataLen/PAGE_COUNT+1;
                    if(pageCount == 1){
                        goodsStock.addAll(tmpGoodsStock.subList(0,dataLen%PAGE_COUNT == 0?PAGE_COUNT:dataLen));
                    }else{
                        goodsStock.addAll(tmpGoodsStock.subList(0,PAGE_COUNT));
                    }
                    goodsStockAdapter.notifyDataSetChanged();//刷新列表
                    lstGoods.setSelection(0);//默认选中第一项
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_stock);
        ViewUtils.inject(this);
        dbUtils = SQLiteUtils.getInstance(this).getDbUtils();
        goodsStockAdapter = new GoodsStockAdapter(this,goodsStock);
        lstGoods.setAdapter(goodsStockAdapter);
        lstGoods.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                if(scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE
                        && view.getLastVisiblePosition() == view.getCount()-1){
                    currentPageIndex ++;
                    if(currentPageIndex > pageCount-1){
                        currentPageIndex = pageCount - 1;
                        return;
                    }
                    int dataLen = tmpGoodsStock.size();
                    int backPageIndex = currentPageIndex + 1;
                    if(currentPageIndex == pageCount-1){
                        goodsStock.addAll(tmpGoodsStock.subList(PAGE_COUNT*currentPageIndex,
                                dataLen%PAGE_COUNT==0?backPageIndex*PAGE_COUNT
                                        :PAGE_COUNT*currentPageIndex+dataLen%PAGE_COUNT));
                    }else{
                        goodsStock.addAll(tmpGoodsStock.subList(PAGE_COUNT*currentPageIndex,
                                backPageIndex*PAGE_COUNT));
                    }
                    goodsStockAdapter.notifyDataSetChanged();//刷新列表
                }
            }
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            }
        });
    }

    @OnClick(value={R.id.pgoodsStock_txtSearch,R.id.pgoodsStock_txtViewAll,R.id.pgoodsStock_txtFindByBrand,
    R.id.pgoodsStock_txtClear})
    public void onViewClick(View v){
        switch(v.getId()){
            case R.id.pgoodsStock_txtSearch:
                String keyword = etSearch.getText().toString();
                if(TextUtils.isEmpty(keyword)){
                    Toast.makeText(this,"查询关键字不能为空!",Toast.LENGTH_SHORT).show();
                    return;
                }
                operType = 1;//设置为当前操作类型为查询关键字
                findAllGoodsStockByKeyword(this, keyword,isHasStock,isHasNegative);//查询商品的库存信息
                break;
            case R.id.pgoodsStock_txtViewAll:
                operType = 2;//设置当前操作类型为查询全部商品
                findAllGoodsStock(this, isHasStock,isHasNegative);//查询所有商品库存信息
                break;
            case R.id.pgoodsStock_txtFindByBrand:
                startActivityForResult(new Intent(this, FindbyBrandActivity.class),0x0001);
                break;
            case R.id.pgoodsStock_txtClear://清空搜索文字
                etSearch.setText("");
                break;
            default:
                break;
        }
    }

    //控制库存查询条件
    @OnCompoundButtonCheckedChange(value={R.id.pgoodsStock_cbStockSelector,R.id.pgoodsStock_cbStockSelector1})
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch(buttonView.getId()){
            case R.id.pgoodsStock_cbStockSelector:
                if(isChecked){
                    isHasStock = true;
                }else{
                    isHasStock = false;
                }
                break;
            case R.id.pgoodsStock_cbStockSelector1:
                if(isChecked){
                    isHasNegative = true;
                }else{
                    isHasNegative = false;
                }
                break;
        }
        reQueryWhenCBChanged();//当CheckBox发生选中的改变时，进行数据重新查询
    }

    @OnItemClick(value = {R.id.pgoodsStock_lstGoods})
    public void onItemClick(AdapterView<?> av,View view, int position,long itemId){
        final HashMap<String,Object> item = (HashMap<String,Object>)lstGoods.getItemAtPosition(position);
        int intKc = Integer.parseInt(item.get("gkc").toString());
        int intHsgx = Integer.parseInt(item.get("ghsgx").toString());
        final MessageBox msgBox = new MessageBox(this);
        msgBox.setMessage("名称：" + item.get("gmc").toString()+"\n"
                +"条码：" + item.get("gtm").toString()+"\n"
                +"规格："+item.get("ggg").toString()+item.get("gdw").toString()+"\n"
                +"库存："+String.valueOf(intKc/intHsgx)+"件"+intKc%intHsgx+"散");
        msgBox.txtCancel.setVisibility(View.GONE);
        msgBox.onPositiveNegitiveClick(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                msgBox.dismiss();
            }
        });
        msgBox.show();
//        if(curIndex == -1) curIndex = position;
//        if (curIndex!=position){
//            clickCount = 0;
//            curIndex = position;
//            Toast.makeText(this,"库存："+item.get("gkc"),Toast.LENGTH_SHORT).show();
//        }else{
//            switch(clickCount){
//                case 0:
//                    Toast.makeText(this,"库存："+item.get("gkc"),Toast.LENGTH_SHORT).show();
//                    break;
//                case 1:
//                    Toast.makeText(this,"再点也没有多余库存啦!",Toast.LENGTH_SHORT).show();
//                    break;
//                case 2:
//                    Toast.makeText(this,"别再点啦!要不您更新更新!",Toast.LENGTH_SHORT).show();
//                    break;
//                case 3:
//                    Toast.makeText(this,"请您不要再点了!真的没有了!",Toast.LENGTH_SHORT).show();
//                    break;
//                case 4:
//                    Toast.makeText(this,"真的没有了!我也没有办法!",Toast.LENGTH_SHORT).show();
//                    break;
//                case 5:
//                    Toast.makeText(this,"真的木有了!我保证!",Toast.LENGTH_SHORT).show();
//                    break;
//                default:
//                    Toast.makeText(this,"额!强迫症，伤不起 - -!!!",Toast.LENGTH_SHORT).show();
//                    break;
//            }
//            clickCount++;
//        }
    }

    /**
     * 当CheckBox发生选中的改变时，进行数据重新查询
     */
    public void reQueryWhenCBChanged(){
        //根据操作类型进行相应的查询
        switch(operType){
            case 1:
                String keyword = etSearch.getText().toString();
                if(!TextUtils.isEmpty(keyword)){
                    findAllGoodsStockByKeyword(this, keyword,isHasStock,isHasNegative);//查询商品的库存信息
                }
                else{//清空现在的列表
                    resetGoodsStock();
                }
                break;
            case 2:
                findAllGoodsStock(this, isHasStock,isHasNegative);//查询所有商品库存信息
                break;
            case 3:
                if(recorBrandId <= 0){
                    resetGoodsStock();//清空现在的列表
                    return;
                }
                findAllGoodsStockByBrandId(this,recorBrandId,isHasStock,isHasNegative);//查询某品牌下的所有商品的库存信息
                break;
        }
    }

    /**
     * 查询商品的库存信息
     * @param context
     * @param keyword
     */
    public void findAllGoodsStockByKeyword(final Context context,final String keyword,final boolean isHasStock,final boolean isHasNegative){
        new AsyncTask<Void,Void,Void>(){
            private List<HashMap<String,Object>> list = null;
            private String errMessage = null;
            private ProgressDialog dialog = null;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(context,"","正在查询...");
            }

            @Override
            protected Void doInBackground(Void... params) {
                try{
                    list = FreporterDbHelper.findAllGoodsStockByKeyword(dbUtils, keyword,isHasStock,isHasNegative);
                }catch (Exception e){
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                if(errMessage!=null){
                    resetGoodsStock();//重置商品库存数据
                    Toast.makeText(context,"查询失败！原因："+errMessage,Toast.LENGTH_SHORT).show();
                    return;
                }
                if(list == null || list.size()<=0){
                    resetGoodsStock();//重置商品库存数据
                    Toast.makeText(context,"无相关商品信息!",Toast.LENGTH_SHORT).show();
                    return;
                }
                handler.obtainMessage(MSG_REFRESH_GOODS_STOCK_LISTVIEW,list).sendToTarget();
            }
        }.execute();
    }

    /**
     * 查询所有商品的库存信息
     * @param context
     */
    public void findAllGoodsStock(final Context context,final boolean isHasStock,final boolean isHasNegative){
        new AsyncTask<Void,Void,Void>(){
            private List<HashMap<String,Object>> list = null;
            private String errMessage = null;
            private ProgressDialog dialog = null;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(context,"","正在查询...");
            }

            @Override
            protected Void doInBackground(Void... params) {
                try{
                    list = FreporterDbHelper.findAllGoodsStock(dbUtils,isHasStock,isHasNegative);
                }catch (Exception e){
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                if(errMessage!=null){
                    resetGoodsStock();//重置商品库存数据
                    Toast.makeText(context,"查询失败！原因："+errMessage,Toast.LENGTH_SHORT).show();
                    return;
                }
                if(list == null || list.size()<=0){
                    resetGoodsStock();//重置商品库存数据
                    Toast.makeText(context,"无相关商品信息!",Toast.LENGTH_SHORT).show();
                    return;
                }
                handler.obtainMessage(MSG_REFRESH_GOODS_STOCK_LISTVIEW,list).sendToTarget();
            }
        }.execute();
    }

    /**
     * 查询某品牌下的商品的库存信息
     * @param context
     */
    public void findAllGoodsStockByBrandId(final Context context,final int brandId,final boolean isHasStock,final boolean isHasNegative){
        new AsyncTask<Void,Void,Void>(){
            private List<HashMap<String,Object>> list = null;
            private String errMessage = null;
            private ProgressDialog dialog = null;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                dialog = ProgressDialog.show(context,"","正在查询...");
            }

            @Override
            protected Void doInBackground(Void... params) {
                try{
                    list = FreporterDbHelper.findAllGoodsStockByBrandId(dbUtils, brandId, isHasStock,isHasNegative);
                }catch (Exception e){
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(Void aVoid) {
                super.onPostExecute(aVoid);
                if(dialog!=null && dialog.isShowing()) dialog.dismiss();
                if(errMessage!=null){
                    resetGoodsStock();//重置商品库存数据
                    Toast.makeText(context,"查询失败！原因："+errMessage,Toast.LENGTH_SHORT).show();
                    return;
                }
                if(list == null || list.size()<=0){
                    resetGoodsStock();//重置商品库存数据
                    Toast.makeText(context,"无相关品牌的商品信息!",Toast.LENGTH_SHORT).show();
                    return;
                }
                handler.obtainMessage(MSG_REFRESH_GOODS_STOCK_LISTVIEW,list).sendToTarget();
            }
        }.execute();
    }

    /**
     * 重置商品库存数据
     */
    public void resetGoodsStock(){
        currentPageIndex = 0;
        pageCount = 0;
        tmpGoodsStock.clear();
        goodsStock.clear();
        goodsStockAdapter.notifyDataSetChanged();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        recorBrandId = -1;//默认记录的品牌号为-1
        if(requestCode == 0x0001 && resultCode == Activity.RESULT_OK && data!=null){
            operType = 3;//设置当前操作位查询某品牌下的商品
            int brandId = data.getIntExtra("brandId",0);
            recorBrandId  = brandId;//记录品牌号，用于记录查询
            findAllGoodsStockByBrandId(this,brandId,isHasStock,isHasNegative);//查询某品牌下的所有商品的库存信息
        }
    }

    /**
     * 页面返回
     */
    public void goBack() {
        this.finish();
        overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
    }

    @OnClick(value = {R.id.pgoodsStock_imgBack})
    public void OnBackClick(View view) {
        goBack();//页面返回
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_BACK) {
            goBack();//页面返回
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
